<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/22 0022
 * Time: 14:58
 */

namespace app\finance\controller;


use think\Db;

class SalarybackController extends BaseController
{
    public function index()
    {
        return $this->fetch();
    }

    /**
     *创建
     */
    public function addSalaryBack()
    {
        echo $this->fetch();
    }

    /**
     * 保存创建数据
     * @return mixed
     */
    public function ajaxAddSalaryBack()
    {
        if(!empty($_POST)){
            $addData = $this->request->post('addData');
            $addResult = Db::table('salary_bak')->data($addData)->insert();
            if($addResult) return $this->ajaxSuccess();
        }
        return $this->ajaxFail();
    }

    /**
     *编辑
     */
    public function editUser()
    {
        $userId = $this->request->get('user_id');
        if(!is_numeric($userId))return $this->ajaxFail(0,'参数错误');
        $userInfo = Db::table('user_info')->where('id', '=', $userId)->find();
        if(empty($userInfo)) return '该用户已经不存在';
        $this->assign('userInfo', $userInfo);
        echo $this->fetch();
    }
    /**
     * 保存编辑数据
     * @return mixed
     */
    public function ajaxEditUser()
    {
        if(!empty($_POST)){
            $addUserData = $this->request->post('UserData');
            unset($addUserData['pass_word_affirm']);
            $isExist = Db::table('user_info')
                ->where('user_name', '=', $addUserData['user_name'])
                ->where('id', 'neq', $addUserData['id'])
                ->find();
            if(!empty($isExist))return $this->ajaxFail(0, '该用户已经存在，请确认');

            $Result = Db::table('user_info')->data($addUserData)->update();
            if($Result) return $this->ajaxSuccess();
        }
        return $this->ajaxFail();
    }

    /**
     * @return array
     * search
     */
    public function ajaxSalaryBackChaXun()
    {
        $map = array();
        if(session('user_name') != 'admin') $map[] = array('user_name', 'eq', session('user_name'));
        if(!empty($_GET) and (isset($_GET['name']) or isset($_GET['card_num']))){
            if(session('user_name') == 'admin') if(!empty($_GET['name'])) $map[] = ['user_name','like', '%' . $_GET['name'] . '%'];
            if(!empty($_GET['card_num'])) $map[] = array('card_num', '=',$_GET['card_num']);
            $array = Db::table('salary_bak')->where($map)->order('id','desc')->select();
            $count = Db::table('salary_bak')->where($map)->count();
            $data = array('code' => 0, 'msg' => '', 'count' => $count, 'data' => $array);
            return $data;
        }
        $page = empty($_GET['page']) ? 1 :$_GET['page'];
        $limit = empty($_GET['limit']) ? 15 :$_GET['limit'];
        $array = Db::table('salary_bak')->where($map)->limit($page - 1, $limit)->order('id','desc')->select();
        $count = Db::table('salary_bak')->count();
        $data = array('code' => 0, 'msg' => '', 'count' => $count, 'data' => $array);
        return $data;
    }

    /**
     * 上传excel文件
     */
    public function uploadExcel()
    {
        $file = $this->request->file('file');
        $isAlreadyUpload = Db::table('file_path')
            ->where(array('file_name' => array('eq', $file->getInfo('name'))))
            ->order('id', 'desc')
            ->find();
        //检查一下文件是否已经导入过？
        if($isAlreadyUpload){
            $fileInfo = $file->validate(['ext'=>'xlsx,xls'])->move('./excel/',true,false);
            if($fileInfo){
                $data = array();
                $data['file_name'] = $_FILES['file']['name'];
                $data['file_path'] = $fileInfo->getSaveName();
                $data['create_time'] = date('Y-m-d H:i:s');
                $insertRes = Db::table('file_path')->data($data)->insert();
                if(!$insertRes)  return $this->ajaxFail();
//                return $this->ajaxSuccess(1,'',array('file_id'=> Db::getLastInsID()));
                return $this->ajaxSuccess(2, '该文件已经导入，是否重新导入',array('old_file_id' => $isAlreadyUpload['id'],'file_id'=> Db::getLastInsID()));
            }else{
                return $this->ajaxFail(0, $file->getError());
            }
        }

        $fileInfo = $file->validate(['ext'=>'xlsx,xls'])->move('./excel/',true,false);
        if($fileInfo){
            $data = array();
            $data['file_name'] = $_FILES['file']['name'];
            $data['file_path'] = $fileInfo->getSaveName();
            $data['create_time'] = date('Y-m-d H:i:s');
            $insertRes = Db::table('file_path')->data($data)->insert();
            if(!$insertRes)  return $this->ajaxFail();
            return $this->ajaxSuccess(1,'',array('file_id'=> Db::getLastInsID()));
        }else{
            return $this->ajaxFail(0, $file->getError());
        }
    }

    /**
     * 获取上传文件的数据
     */
    public function getUploadFileData()
    {
        $file_id = $this->request->post('file_id');
        $type = $this->request->post('type');
        if($type == 0){
            //选择覆盖，删除之前导入的数据
            $old_file_id = $this->request->post('old_file_id');
            Db::table('salary_bak')->where(array('from_excel_id' => array('eq', $old_file_id)))->delete();
        }
        $fileInfo = Db::table('file_path')->where(array('id' => array('eq', $file_id)))->find();
        if(empty($fileInfo)) $this->ajaxFail(0, '文件不有问题,请联系管理员');
        $filePath = getRealDir() .'/public/excel/' . $fileInfo['file_path'];
        if(!file_exists($filePath)) $this->ajaxFail(0, '文件不存在,请联系管理员');
        $data = import_excel($filePath);

        $insertData = array();
        $fieldArray = array(
            'user_name',
            'reasons_for_increas',
            'reasons_time',
            'monthly_salary_increase',
            'replacement_months',
            'salary_bak',
            'deduct_more_amount',
            'remark',
        );
        foreach ($data  as $key => $datum) {
            foreach ($datum as $index => $item) {
                $insertData[$key][$fieldArray[$index]] = $item;
                $insertData[$key]['from_excel_id'] = $file_id;
            }
        }

        $result = Db::table('salary_bak')->data($insertData)->limit(100)->insertAll();
        if(!$result)  return $this->ajaxFail();
        return $this->ajaxSuccess();
    }

    /**
     * 导出文件
     */
    public function exportFile()
    {
        //是否根据条件导出
        $map = array();
        if(session('user_name') != 'admin') $map['real_name'] = array('eq', session('user_name'));
        if(!empty($_POST) and (!empty($_POST['name']) or !empty($_POST['card_num']) or !empty($_POST['checkIdS']))){
            if(!empty($_POST['name'])) $map[] = ['user_name','=',$_POST['name']];
            if(!empty($_POST['card_num'])) $map[] = array('card_num', '=',$_POST['card_num']);
            if(!empty($_POST['checkIdS'])) $map[] = array('id','in', trim($_POST['checkIdS'],','));
        }

        $xlsData = Db::table('salary_bak')->where($map)->order('id','desc')->select();
        $objExcel = new \PHPExcel();
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
        $objActSheet = $objExcel->getActiveSheet();
        $letter =explode(',',"A,B,C,D,E,F,G,H");
        $arrHeader = array(
         '人员名称'
        ,'增（减）原因'
        ,'增（减）时间'
        ,'月工资增（减）额'
        ,'补发月数'
        ,'本月补发工资'
        ,'扣减多发金额'
        ,'备注'
        );
        $lenth =  count($arrHeader);
        //设置第一行标题  XXXX年XX月工资发放表
        $objExcel->getActiveSheet()->mergeCells('A1:H1');//合并单元格
        $objActSheet->setCellValue('A1', '工资补发情况明细表');
        //垂直居中显示
        $objExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置字体大小
        $objExcel->getActiveSheet()->getStyle("A1")->getFont()->setBold(true)
            ->setSize(18);
        for($i = 0;$i < $lenth;$i++) {
            $objActSheet->setCellValue("$letter[$i]2","$arrHeader[$i]");
        };
        foreach($xlsData as $k=>$v){
            $k +=3;
            $objActSheet->setCellValue('A'.$k, $v['user_name']);
            $objActSheet->setCellValue('B'.$k, $v['reasons_for_increas']);
            $objActSheet->setCellValue('C'.$k, $v['reasons_time']);
            $objActSheet->setCellValue('D'.$k, $v['monthly_salary_increase']);
            $objActSheet->setCellValue('E'.$k, $v['replacement_months']);
            $objActSheet->setCellValue('F'.$k, $v['salary_bak']);
            $objActSheet->setCellValue('G'.$k, $v['deduct_more_amount']);
            $objActSheet->setCellValue('H'.$k, $v['remark']);

            $objActSheet->getRowDimension($k)->setRowHeight(20);
        }
        $width = array(20,20,25,25,25,20,20,20);
        //设置表格的宽度
        $objActSheet->getColumnDimension('A')->setWidth($width[0]);
        $objActSheet->getColumnDimension('B')->setWidth($width[1]);
        $objActSheet->getColumnDimension('C')->setWidth($width[2]);
        $objActSheet->getColumnDimension('D')->setWidth($width[3]);
        $objActSheet->getColumnDimension('E')->setWidth($width[4]);
        $objActSheet->getColumnDimension('F')->setWidth($width[5]);
        $objActSheet->getColumnDimension('G')->setWidth($width[6]);
        $objActSheet->getColumnDimension('H')->setWidth(20);

        $outfile = "工资补发情况明细表.xlsx";
        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$outfile.'"');
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter->save('php://output');    //这里直接导出文件
    }
    /**
     *删除工资发发放表
     */
    public function delete()
    {
        if(!empty($_POST) and isset($_POST['checkIdS'])){
            $checkIdArray = explode(',', trim($_POST['checkIdS'], ','));
            $delResult = Db::table('salary_bak')->delete($checkIdArray);
            if($delResult) return $this->ajaxSuccess();
        }
        return $this->ajaxFail();
    }
}